﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.UI.YGUI;

/// <summary>
/// 对MeshRenderer类 
/// </summary>
public class MeshRendererWrap : MonoBehaviour
{
    private string m_materialName;
    private MeshRenderer m_target;
    
    private Material m_defaultMaterial;
    
    private ResLoader _resLoaderMaterial;

    private ResLoader _oldResLoaderMaterial;
    
    public string materialName
    {
        get
        {
            return m_materialName;
        }
        set
        {
            if (m_materialName == value)
                return;
            m_materialName = value;
            
            //检查需要操作的对象是否存在
            CheckTarget();
            
            if (string.IsNullOrEmpty(value))
            {
                m_target.material = null;
                _oldResLoaderMaterial?.Recycle2Cache();
                _oldResLoaderMaterial = null;
                _resLoaderMaterial?.Recycle2Cache();
                _resLoaderMaterial = null;
                return;
            }
            _oldResLoaderMaterial = _resLoaderMaterial;
                
            _resLoaderMaterial = ResLoader.Alloc();
            _resLoaderMaterial.Add2Load("Assets/ResourcesAssets/" + value + ".mat",
                (success, name, asset) =>
                {
                    if (!success)
                    {
                        m_target.material = m_defaultMaterial;
                        UnityEngine.Debug.LogError("dont has this material:" + value);
                    }
                    else
                    {
                        var mat = asset as Material;
                        m_target.material = mat;
                    }
                    _oldResLoaderMaterial?.Recycle2Cache();
                    _oldResLoaderMaterial = null;
                }).Load();
        }
    }

    void OnDestroy()
    {
        m_materialName= string.Empty;
        m_target.material = m_defaultMaterial;
        
        _resLoaderMaterial?.Recycle2Cache();
        _resLoaderMaterial = null;
        _oldResLoaderMaterial?.Recycle2Cache();
        _oldResLoaderMaterial = null;
    }
    
    /// <summary>
    /// 检查需要操作的对象是否存在
    /// </summary>
    void CheckTarget()
    {
        if (m_target == null)
        {
            m_target = transform.GetComponent<MeshRenderer>();
            m_defaultMaterial = m_target.material;
        }
    }
}
